package com.mingzhi.permissionservice.service.impl;

import com.mingzhi.permissionservice.entity.UserRoles;
import com.mingzhi.permissionservice.repository.PermissionRepository;
import com.mingzhi.permissionservice.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionRepository permissionRepository;

    @Override
    public Integer bindDefaultRole(Long userId) {
        UserRoles userRoles = new UserRoles();
        userRoles.setUserId(userId);
        return permissionRepository.bindDefaultRole(userRoles);
    }

    @Override
    public String getUserRoleCode(Long userId) {
        if (userId == null || userId <= 0) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        //先查询角色ID是否存在
        Integer roleId = permissionRepository.getRoleIdByUserId(userId);
        if (roleId == null) {
            return null;
        }
        //从数据库获取角色名
        return permissionRepository.getRoleCode(userId);
    }

    /**
     * 升级用户为管理员
     *
     * @param userId
     */
    @Override
    public void upgradeToAdmin(Long userId) {
        permissionRepository.upgradeToAdmin(userId);
    }

    /**
     * 降级用户为普通用户
     *
     * @param userId
     */
    @Override
    public void downgradeToUser(Long userId) {
        permissionRepository.downgradeToUser(userId);
    }

    /**
     * 获取所有普通用户id
     * @return
     */
    @Override
    public List<Long> getNormalUserIds() {
        return permissionRepository.getUserIdsByRoleId(2);
    }
}
